from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class PeriodicTaskConfig(models.Model):
	name = models.CharField(max_length=64, unique=True, verbose_name='任务名称')
	task = models.CharField(max_length=128, verbose_name='任务路径')
	crontab = models.CharField(max_length=32, verbose_name='定时表达式')
	enabled = models.BooleanField(default=True, verbose_name='是否启用')
	last_run_at = models.DateTimeField(null=True, blank=True, verbose_name='最后运行时间')
	remark = models.TextField(blank=True, verbose_name='备注')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')

	def __str__(self):
		return self.name


class Cards(models.Model):
	id = models.AutoField(primary_key=True, verbose_name='ID')
	iccid = models.CharField(max_length=32, null=True, blank=True, verbose_name='ICCID')
	msisdn = models.CharField(max_length=20, null=True, blank=True,verbose_name='MSISDN')
	imsi = models.CharField(max_length=20, null=True, blank=True, verbose_name='IMSI')
	imei = models.CharField(max_length=20, null=True, blank=True, verbose_name='IMEI')
	cardType = models.CharField(max_length=8, null=True, blank=True, verbose_name='卡类型')
	cardStatus = models.CharField(max_length=8, null=True, blank=True, verbose_name='卡状态')
	operator = models.CharField(max_length=8, null=True, blank=True, verbose_name='运营商')
	packageName = models.CharField(max_length=64, null=True, blank=True, verbose_name='套餐名称')
	totalFlow = models.CharField(max_length=16, null=True, blank=True, verbose_name='套餐总流量')
	cardFlow = models.CharField(max_length=16, null=True, blank=True, verbose_name='已使用流量')
	leftFlow = models.CharField(max_length=16, null=True, blank=True, verbose_name='卡剩余流量')
	lastActivateTime = models.DateField(null=True, blank=True, verbose_name='最后激活时间')
	activateTime = models.DateField(null=True, blank=True, verbose_name='激活时间')
	packageTime = models.DateField(null=True, blank=True, verbose_name='套餐到期时间')
	remark = models.TextField(null=True, blank=True, verbose_name='备注')
	realNameStatus = models.CharField(max_length=8, null=True, blank=True, verbose_name='实名状态')
	channelId = models.CharField(max_length=8, null=True, blank=True, verbose_name='渠道ID')
	packageId = models.CharField(max_length=8, null=True, blank=True, verbose_name='套餐ID')
	priceTime = models.IntegerField(null=True, blank=True, verbose_name='计费周期')
	poolId = models.CharField(max_length=8, null=True, blank=True, verbose_name='池ID')
	networkType = models.CharField(max_length=8, null=True, blank=True, verbose_name='网络类型')
	packageTotalFlow = models.CharField(max_length=16, null=True, blank=True, verbose_name='套餐总流量(原始)')
	isRealName = models.CharField(max_length=8, null=True, blank=True, verbose_name='是否实名')
	offTime = models.DateField(null=True, blank=True, verbose_name='停机时间')
	dismantleTime = models.DateTimeField(auto_now=True, null=True, blank=True, verbose_name='销户时间')
	orderId = models.CharField(max_length=32, null=True, blank=True, verbose_name='订单ID')
	buyTime = models.DateTimeField(auto_now=True, null=True, blank=True, verbose_name='购买时间')
	openCardTime = models.DateTimeField(auto_now=True, null=True, blank=True, verbose_name='开卡日期（卡片出库时间）')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='时间')
	updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
	api_at = models.DateTimeField(null=True, blank=True, verbose_name='接口更新时间')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"{self.iccid}"

class Log(models.Model):
	ACTION_CHOICES = [
		('login', '登录'),
		('add_role', '添加角色'),
		('edit_role', '编辑角色'),
		('delete_role', '删除角色'),
		('other', '其他'),
	]
	user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='用户')
	action = models.CharField(max_length=32, choices=ACTION_CHOICES, verbose_name='操作类型')
	detail = models.TextField(verbose_name='详情', blank=True)
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='时间')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')

	def __str__(self):
		return f"{self.user} {self.get_action_display()} {self.created_at}"


class SystemConfig(models.Model):
	id = models.AutoField(primary_key=True, verbose_name='ID')
	name = models.CharField(max_length=128, blank=True, verbose_name='名称')
	# 1文本框 2多行文本 3选择框
	type = models.IntegerField(choices=[(1,'文本框'),(2,'多行文本'),(3,'选择框')], default=1, verbose_name='类型')
	options = models.CharField(max_length=2048, blank=True, verbose_name='选项（选择框时竖线分割）')
	key = models.CharField(max_length=64, unique=True, verbose_name='参数名')
	value = models.CharField(max_length=2048, verbose_name='参数值')
	remark = models.CharField(max_length=128, blank=True, verbose_name='备注')
	def __str__(self):
		return f"{self.key}: {self.value}"

	@staticmethod
	def get_system_title():
		"""获取系统标题"""
		title_config = SystemConfig.objects.filter(key='title').first()
		return title_config.value if title_config else '物流卡系统'

class UserProfile(models.Model):
	user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
	realname = models.CharField(max_length=32, blank=True, verbose_name='真实姓名')
	type = models.CharField(max_length=32, choices=[('admin', '管理员'), ('user', '普通用户'), ('config_user', '配置用户')], default='user')
	operator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='created_users', verbose_name='创建者用户ID')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')

# 卡和客户关联表
class CardUserRelation(models.Model):
	customer = models.ForeignKey('Customer', on_delete=models.CASCADE,null=True, blank=True, verbose_name='客户ID')
	card = models.ForeignKey(Cards, on_delete=models.CASCADE, verbose_name='卡ID')
	operator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='card_operator', verbose_name='操作人ID')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='操作时间')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"客户:{self.customer_id} 卡:{self.card_id} 时间:{self.created_at}" 

# 订单管理
class CardOrder(models.Model):
	ORDER_TYPE_CHOICES = [
		('buy', '购卡'),
		('renew', '续费'),
	]
	STATUS_CHOICES = [
		('pending', '未支付'),
		('paid', '已支付未发货'),
		('completed', '已完成'),
	]
	order_type = models.CharField(max_length=16, choices=ORDER_TYPE_CHOICES, default='buy', verbose_name='订单类型')
	order_no = models.CharField(max_length=32, unique=True, verbose_name='订单号')
	customer = models.ForeignKey('Customer', on_delete=models.CASCADE, verbose_name='下单客户', null=True, blank=True)
	package = models.CharField(max_length=64, blank=True, verbose_name='套餐')
	card_count = models.IntegerField(default=1, verbose_name='卡数')
	amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='金额')
	status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='pending', verbose_name='订单状态')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
	updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
	paid_at = models.DateTimeField(null=True, blank=True, verbose_name='支付时间')
	remark = models.TextField(blank=True, verbose_name='备注')
	receiver = models.CharField(max_length=32, blank=True, verbose_name='收件人')
	delivery_phone = models.CharField(max_length=20, blank=True, verbose_name='收货电话')
	delivery_address = models.CharField(max_length=256, blank=True, verbose_name='收货地址')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"{self.order_no} - {self.card_count}张"

# 订单附属表：保存订单卡号
class CardOrderCard(models.Model):
		id = models.AutoField(primary_key=True, verbose_name='ID')
		order = models.ForeignKey(CardOrder, on_delete=models.CASCADE, related_name='order_cards', verbose_name='订单')
		card = models.ForeignKey('Cards', on_delete=models.CASCADE, verbose_name='卡')
		created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
		delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
		def __str__(self):
			return f"订单:{self.order_id} 卡:{self.card_id}"

class Address(models.Model):
	customer = models.ForeignKey('Customer', on_delete=models.CASCADE, verbose_name='客户', null=True, blank=True, related_name='delivery_addresses')
	receiver = models.CharField(max_length=32, verbose_name='收件人')
	phone = models.CharField(max_length=20, verbose_name='手机号')
	address = models.CharField(max_length=256, verbose_name='地址详情')
	remark = models.CharField(max_length=128, blank=True, verbose_name='备注')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
	updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		if self.customer:
			return f"{self.customer.username} - {self.address}"
		return f"{self.address}"

# 客户与单价配置
class Customer(models.Model):
	username = models.CharField(max_length=32, unique=True, verbose_name='用户名')
	user = models.OneToOneField('auth.User', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='系统用户')
	company_name = models.CharField(max_length=64, verbose_name='公司名')
	phone = models.CharField(max_length=20, verbose_name='手机号')
	address = models.CharField(max_length=256, verbose_name='公司地址')
	email = models.EmailField(max_length=128, verbose_name='邮箱')
	remark = models.CharField(max_length=128, blank=True, verbose_name='备注')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
	updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"{self.username} - {self.company_name}"

class UserPriceConfig(models.Model):
	customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True,verbose_name='客户')
	package = models.CharField(max_length=64, verbose_name='资费包')
	channel_no = models.CharField(max_length=32, verbose_name='通道号')
	price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='单价')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
	updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"{self.customer.username} - {self.package} - {self.price}"

# 流量池与池卡关系、销户
class CardPool(models.Model):
	name = models.CharField(max_length=64, verbose_name='池名称')
	owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='所属用户')
	total_flow = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='总流量')
	remain_flow = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='剩余流量')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
	updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
	remark = models.CharField(max_length=128, blank=True, verbose_name='备注')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"{self.name} - {self.owner.username}"

class PoolCardRelation(models.Model):
	pool = models.ForeignKey(CardPool, on_delete=models.CASCADE, verbose_name='流量池')
	card = models.ForeignKey('Cards', on_delete=models.CASCADE, verbose_name='卡')
	added_at = models.DateTimeField(auto_now_add=True, verbose_name='加入时间')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"池:{self.pool_id} 卡:{self.card_id}"

class CardDeactivation(models.Model):
	card = models.ForeignKey('Cards', on_delete=models.CASCADE, verbose_name='卡')
	reason = models.CharField(max_length=128, verbose_name='销户原因')
	deactivated_at = models.DateTimeField(auto_now_add=True, verbose_name='销户时间')
	remark = models.CharField(max_length=128, blank=True, verbose_name='备注')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"卡:{self.card_id} 销户时间:{self.deactivated_at}"

# 费用与预警
class FeeDetail(models.Model):
	user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
	card = models.ForeignKey('Cards', on_delete=models.CASCADE, verbose_name='卡')
	amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='消费金额')
	fee_type = models.CharField(max_length=32, verbose_name='费用类型')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='消费时间')
	remark = models.CharField(max_length=128, blank=True, verbose_name='备注')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"{self.user.username} - {self.card_id} - {self.amount}"

class FlowWarning(models.Model):
	card = models.ForeignKey('Cards', on_delete=models.CASCADE, verbose_name='卡')
	threshold = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='预警阈值')
	current_flow = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='当前流量')
	is_active = models.BooleanField(default=True, verbose_name='是否激活')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
	updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"卡:{self.card_id} 流量:{self.current_flow}/{self.threshold}"

class FlowWarningRecord(models.Model):
	warning = models.ForeignKey(FlowWarning, on_delete=models.CASCADE, verbose_name='预警配置')
	triggered_at = models.DateTimeField(auto_now_add=True, verbose_name='触发时间')
	remark = models.CharField(max_length=128, blank=True, verbose_name='备注')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
	def __str__(self):
		return f"预警:{self.warning_id} 时间:{self.triggered_at}"

class CardExpireReminder(models.Model):
	card = models.ForeignKey('Cards', on_delete=models.CASCADE, verbose_name='卡')
	expire_date = models.DateField(verbose_name='到期时间')
	reminded = models.BooleanField(default=False, verbose_name='是否已提醒')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
	remark = models.CharField(max_length=128, blank=True, verbose_name='备注')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
 
# 菜单管理模块
class Menu(models.Model):
	"""
	菜单管理模块，存储系统菜单信息
	"""
	name = models.CharField(max_length=64, verbose_name='菜单名称')
	icon = models.CharField(max_length=32, blank=True, verbose_name='图标')
	url = models.CharField(max_length=128, blank=True, verbose_name='跳转链接')
	order = models.IntegerField(default=0, verbose_name='排序')
	is_active = models.BooleanField(default=True, verbose_name='是否启用')
	parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, verbose_name='父菜单')
	remark = models.CharField(max_length=128, blank=True, verbose_name='备注')
	# 权限字段：0全部显示，1仅管理员，2仅普通用户，3仅配置用户，4仅配置用户与管理员，5仅管理员与普通用户
	permission = models.IntegerField(default=0, choices=[(0,'全部'),(1,'仅管理员'),(2,'仅普通用户'),(3,'仅配置用户'),(4,'仅配置用户与管理员'),(5,'仅管理员与普通用户')], verbose_name='显示权限')
	# 状态字段：是否显示菜单
	status = models.BooleanField(default=True, verbose_name='是否显示')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
	updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')

	def __str__(self):
		return self.name

	@staticmethod
	def ensure_system_config_menu():
		if not Menu.objects.filter(url='/system_config_manage/', delete_at__isnull=True).exists():
			Menu.objects.create(
				name='系统参数管理',
				icon='gear',
				url='/system_config_manage/',
				order=999,
				is_active=True,
				status=True,
				permission=1,
				remark='系统参数管理入口'
			)
# 资费包管理模块
class Package(models.Model):
	"""
	资费包管理模块
	"""
	name = models.CharField(max_length=64, unique=True, verbose_name='资费包名称')
	description = models.TextField(blank=True, verbose_name='资费包描述')
	price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='价格')
	created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
	updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
	remark = models.CharField(max_length=128, blank=True, verbose_name='备注')
	delete_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')

	def __str__(self):
		return self.name

class PaymentRecord(models.Model):
    order = models.ForeignKey(CardOrder, on_delete=models.CASCADE, verbose_name='系统订单')
    wx_trade_no = models.CharField(max_length=64, verbose_name='微信支付订单号')
    out_trade_no = models.CharField(max_length=64, verbose_name='商户订单号')
    pay_time = models.DateTimeField(null=True, blank=True, verbose_name='支付时间')
    is_paid = models.BooleanField(default=False, verbose_name='是否支付')
    raw_notify = models.TextField(blank=True, verbose_name='微信回调原始内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    def __str__(self):
        return f"{self.order.order_no} - {self.wx_trade_no} - {self.is_paid}"